import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';
import { CommonModule } from '@angular/common';
import { BehaviorSubject, Subject } from 'rxjs';
import { FormBuilder, FormControl, UntypedFormGroup, Validators } from '@angular/forms';
import { UserPassword } from 'src/app/models/bo/user-password';
import { UserDto } from 'src/app/models/sys/user.dto';

@Component({
  selector: 'app-reset-password',
  templateUrl: './reset-password.component.html',
  styleUrl: './reset-password.component.css'
})
export class ResetPasswordComponent implements OnInit {
  @Input() userSubject!: BehaviorSubject<UserDto>;
  @Output() resetEvent = new EventEmitter<UserPassword>();

  updateForm!: UntypedFormGroup;
  userId?: number;

  passwordVisible = false;

  constructor(private _fb: FormBuilder) {
    this.createForm();
  }

  ngOnInit(): void {
    this.userSubject.subscribe((value) => {
      this.userId = value.userId;
      this.updateForm.get('username')?.patchValue(value.username);
      console.log('To disable username');
      this.updateForm.get('username')?.disable();
    });
  }

  createForm() {
    this.updateForm = this._fb.group({
      username: new FormControl(""),
      password: new FormControl('', [Validators.required, Validators.minLength(6), Validators.maxLength(20)])
    });
  }

  onUpdate() {
    if (this.userId == null) {
      this.resetEvent.emit(undefined);
      return;
    }

    const param = new UserPassword();
    param.userId = this.userId;
    param.password = this.updateForm.get('password')?.value;

    this.resetEvent.emit(param);
  }

  onCancel(event: UIEvent) {
    event.preventDefault();

    this.resetEvent.emit(undefined);
  }

}
